import sys
import socket
import urllib
import urllib2
import cookielib
import re
import os

class tinyurl:
	
	NEW_URI = "http://tinyurl.com/api-create.php?url=%s"
	
	def __init__(self, url):
		self.url = url
	
	def create(self):
		encoded_url = urllib.urlencode({'url':self.url})[4:]
		new_url = tinyurl.NEW_URI % (encoded_url)
		tinyurl_request = urllib2.Request(new_url)
		tinyurl_handle = urllib2.urlopen(tinyurl_request)
		return tinyurl_handle.read()

class twitter:
	
	UPDATE_URI = "http://twitter.com/statuses/update.xml"
	
	def __init__(self, username, password):
		self.username = username
		self.password = password
		self.realm = None
		self.toplevel = 'http://twitter.com/statuses/'
	
	def truncate(self, string, target):
		if len(string) > target:
			return string[:(target-3)] + "..."
		return string	
	
	def update(self, status):
		status = self.truncate(status, 140)
		data = self.url_encode_status_message(status)
		response = self.send_update_request(data)
		return response
	
	def url_encode_status_message(self, status):
		data = {'type' : 'post', 'status' : status, 'source' : 'lensherr'}
		return urllib.urlencode(data)
	
	def send_update_request(self, data):
		auth = urllib2.HTTPPasswordMgrWithDefaultRealm()
		auth.add_password(self.realm, self.toplevel, self.username, self.password)
		authHandler = urllib2.HTTPBasicAuthHandler(auth)
		opener = urllib2.build_opener(authHandler)
		urllib2.install_opener(opener)
		socket.setdefaulttimeout(60)
		request = urllib2.Request(twitter.UPDATE_URI, data)
		return urllib2.urlopen(request).read()

class facebook:
	
	FB_LOGIN_URI = "https://login.facebook.com/login.php?m&amp;next=http%3A%2F%2Fm.facebook.com%2Fhome.php"
	FB_MOBILE_URI = "http://m.facebook.com/home.php"
	
	def __init__(self, email, password):
		self.email = email
		self.password = password
		self.cookies = 'fb_cookies.lwp'
		# setup cookie jar :-)
		self.setup_cookie_jar()
	
	def setup_cookie_jar(self):
		jar = cookielib.LWPCookieJar()
		if os.path.isfile(self.cookies):
			jar.load(self.cookies)
		opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(jar))
		urllib2.install_opener(opener)
	
	def get_post_form_id(self):
		request = urllib2.Request(facebook.FB_MOBILE_URI)
		handle = urllib2.urlopen(request)
		html = handle.read()
		post_form_id = re.search('post_form_id" value="([^"]*)"', html).group(1)
		return post_form_id
	
	def update(self, status):
		# let's login....	
		login_data = urllib.urlencode({'email': self.email, 'pass': self.password, 'login': 'Login'})
		login_request = urllib2.Request(facebook.FB_LOGIN_URI, login_data)
		login_handle = urllib2.urlopen(login_request)
		# get the post form id....
		post_form_id = self.get_post_form_id()
		# now let's update our status message....
		status_data = urllib.urlencode({'post_form_id' : post_form_id, 'status': status, 'update':'Update'})
		status_request = urllib2.Request(facebook.FB_MOBILE_URI, status_data)
		status_handle = urllib2.urlopen(status_request)
		return status_handle.read()

class myspace:

	LOGIN_URI = "https://secure.myspace.com/index.cfm?fuseaction=login.process"
	STATUS_URI = "http://www.myspace.com/index.cfm?fuseaction=%s&status=%s&mood=%s&smiley=%s&action=%s&hash=%s&jsonp=%s"

	def __init__(self, email, password):
		self.email = email
		self.password = password
		self.cookies = 'ms_cookies.lwp'
		# setup cookie jar :-)
		self.setup_cookie_jar()

	def setup_cookie_jar(self):
		jar = cookielib.LWPCookieJar()
		if os.path.isfile(self.cookies):
			jar.load(self.cookies)
		opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(jar))
		opener.addheaders = [('User-Agent', 'Mozilla/5.0')]
		urllib2.install_opener(opener)

	def get_status_hash(self, login_html):
		status_hash = re.search('statusMoodService" hash="([^"]*)"', login_html).group(1)
		return status_hash
	
	def generate_status_uri(self, status, status_hash):
		jsonp = "MySpace.Net.JsonpWebServiceProxy._handlers%5B2%5D"
		action = "SaveCustomMoodStatus"
		smiley = "http%3A%2F%2Fx.myspacecdn.com%2Fimages%2Fblog%2Fmoods%2FiBrads%2Ftired.gif"
		mood = "w00t"
		status = urllib.urlencode({'status':status})[7:]
		fuseaction = "statusMoodService"
		status_uri = myspace.STATUS_URI % (fuseaction, status, mood, smiley, action, status_hash, jsonp)
		return status_uri
	
	def update(self, status):
		#let's assemble the login post data
		data = {
			'__VIEWSTATE':'/wEPDwUJNTU4OTgyNDc1ZBgBBR5fX0NvbnRyb2xzUmVxdWlyZVBvc3RCYWNrS2V5X18WAQUnY3RsMDAkY3BNYWluJExvZ2luQm94JFJlbWVtYmVyX0NoZWNrYm94',
			'NextPage':'',
			'ctl00$cpMain$LoginBox$Email_Textbox': self.email,
			'ctl00$cpMain$LoginBox$Password_Textbox': self.password,
			'ctl00_cpMain_LoginBox_Remember_Checkbox':'on',
			'dlb': 'Log In'
		}
		# login
		login_data = urllib.urlencode(data)
		login_request = urllib2.Request(myspace.LOGIN_URI, login_data)
		login_handle = urllib2.urlopen(login_request)
		login_html = login_handle.read()
		status_hash = self.get_status_hash(login_html)
		status_uri = self.generate_status_uri(status, status_hash)
		# status update
		status_request = urllib2.Request(status_uri)
		status_handle = urllib2.urlopen(status_request)
		return status_handle.read()